const subManager = new SubsManager();
const { calculateIndex, enableClickOnTouch } = Utils;
let flag = true;
let timer = '';
let timer1 = ' ';
let flag1 = true;
let flag2 = true;
//let flag3 = true;
// var timer1 = "";
Template.newBoardListHeaderBar.events({
  'click .js-open-archived-board'() {
    Modal.open('archivedBoards');
  },
});

Template.newBoardListHeaderBar.helpers({
  title() {
    return FlowRouter.getRouteName() === 'newHome' ? 'my-boards' : 'public';
  },
  templatesBoardId() {
    return Meteor.user() && Meteor.user().getTemplatesBoardId();
  },
  templatesBoardSlug() {
    return Meteor.user() && Meteor.user().getTemplatesBoardSlug();
  },
});

BlazeComponent.extendComponent({
  onRendered() {
    if (window.screen.width <= 800) {
      document.querySelector('#content').style.marginTop = '96px !important';
    }
    window.onscroll = function() {
      document.body.style.backgroundColor = '';
      document.body.style.backgroundImage =
        "url('./public/../main_backgroundColor.jpg')";
      document.body.style.backgroundSize = 'cover';
      document.body.style.backgroundRepeat = 'no-repeat';
      document.body.style.backgroundAttachment = 'fixed';
    };
    const itemsSelector = '.js-board:not(.placeholder)';
    const $boards = this.$('.js-boards');
    document.body.style.backgroundColor = '';
    document.body.style.backgroundImage =
      "url('./public/../main_backgroundColor.jpg')";
    document.body.style.backgroundSize = 'cover';
    document.body.style.backgroundRepeat = 'no-repeat';
    document.body.style.backgroundAttachment = 'fixed';
    //document.body.classList.add('bg');
    let navHeight = window.getComputedStyle(document.querySelector('.nav'))
      .height;
    document.querySelector('.nav').style.height = navHeight;
    const navlists = document.getElementsByClassName('navlist');
    const navlists1 = document.getElementsByClassName('navlist1');
    for (let i = 0; i < navlists1.length - 1; i++) {
      navlists1[i].onclick = function() {
        // document.querySelector(".wrapper").scrollTop =
        // document.querySelectorAll(".boardlist-section")[i].offsetTop
      };
      document.querySelectorAll('.boardlist-section');
    }
    for (let i = 1; i < navlists.length; i++) {
      navlists[i].onclick = function() {
        if (flag1 == true) {
          for (let i = 1; i < navlists.length; i++) {
            navlists[i].style.backgroundColor = '';
          }
          // if (
          //   this.nextElementSibling.style.display == 'block' ||
          //   this.nextElementSibling.style.display == ''
          // )
          if (this.nextElementSibling.style.height !== '0px') {
            clearTimeout(timer1);
            this.nextElementSibling.style.height = '0px';
            this.nextElementSibling.style.transition = 'all 0.5s';
            //this.nextElementSibling.style.display = 'none';
            if (flag2 == true) {
              navlists[i].querySelector('span').style.transform =
                'rotate(0deg)';
            } else {
              navlists[i].querySelector('span').style.transform =
                'rotate(90deg)';
            }
            for (let i = 0; i < navlists1.length; i++) {
              navlists1[i].style.backgroundColor = '';
              navlists1[i].style.fontWeight = '';
            }
          } else {
            if (flag2 == true) {
              navlists[i].querySelector('span').style.transform =
                'rotate(-90deg)';
            } else {
              navlists[i].querySelector('span').style.transform =
                'rotate(0deg)';
            }
            // this.nextElementSibling.style.display = 'block';
            this.nextElementSibling.style.transition = 'all 0.5s';
            this.nextElementSibling.style.height = navHeight;
            // this.style.backgroundColor="rgba(0,0,0,0.2)";
            this.style.backgroundColor = 'rgba(0,0,0,0.1)';
            for (let i = 0; i < navlists1.length; i++) {
              navlists1[i].style.backgroundColor = '';
              navlists1[i].style.fontWeight = '';
            }
          }
        } else {
          // navlists[i].querySelector(".nav")[i-1].style.height = navHeight;
          this.nextElementSibling.style.height = navHeight;
          this.nextElementSibling.style.transition = 'all 0.5s';
          const navlists = document.getElementsByClassName('navlist');
          for (let i = 1; i < navlists.length; i++) {
            navlists[i].querySelector('span').style.transform = 'rotate(90deg)';
            flag2 = false;
          }
          document.querySelector('.aside').classList.remove('fold');
          document.querySelector('.aside').classList.add('fold1');
          timer = window.setTimeout(function() {
            for (
              let i = 0;
              i < document.querySelectorAll('.list2').length;
              i++
            ) {
              document.querySelectorAll('.list2')[i].style.display =
                'inline-block';
            }
            for (
              let i = 0;
              i < document.querySelectorAll('.icon-xiaoyuhao-').length;
              i++
            ) {
              document.querySelectorAll('.icon-xiaoyuhao-')[i].style.display =
                'block';
            }
          }, 300);
          // for(let i= 0;i< document.querySelectorAll('.nav').length;i++){
          //   document.querySelectorAll('.nav')[i].style.display="block";
          // }
          document.querySelector('.icon-zhankai').style.marginLeft = '200px';
          document.querySelector('.icon-zhankai').style.transition = 'all 0.3s';
          document.getElementsByClassName('icon-zhankai')[0].style.transform =
            'rotate(0deg)';
          document.getElementsByClassName('home-content')[0].style.marginLeft =
            '270px';
          this.querySelector('span').style.transform = 'rotate(0deg)';
          timer1 = window.setTimeout(() => {
            this.nextElementSibling.style.display = 'block';
          }, 300);
          flag1 = true;
          flag = true;
        }
      };
      for (let i = 0; i < navlists1.length; i++) {
        // if (i < 3) {
        navlists1[i].onclick = function() {
          for (let i = 1; i < navlists.length; i++) {
            navlists[i].style.backgroundColor = '';
          }
          for (let i = 0; i < navlists1.length; i++) {
            navlists1[i].style.backgroundColor = '';
            navlists1[i].style.fontWeight = '';
          }
          if (i !== navlists1.length - 1) {
            // document.querySelector(".wrapper").scrollTop =
            let num = document.querySelectorAll('.boardlist-section')[i]
              .offsetTop;
            $(window).animate({ scrollTop: num }, 200);
            window.scrollTo({ top: num, behavior: 'smooth' });
          } else {
            let num = document.querySelectorAll('.boardlist-section2')[0]
              .offsetTop;
            window.scrollTo({ top: num, behavior: 'smooth' });
          }
          this.style.backgroundColor = 'rgba(0,0,0,0.2)';
          this.style.fontWeight = '700';
        };
      }
    }
    $boards.sortable({
      connectWith: '.js-boards',
      tolerance: 'pointer',
      appendTo: '.board-list',
      helper: 'clone',
      distance: 7,
      items: itemsSelector,
      placeholder: 'board-wrapper placeholder',
      start(evt, ui) {
        ui.helper.css('z-index', 1000);
        ui.placeholder.height(ui.helper.height());
        EscapeActions.executeUpTo('popup-close');
      },
      stop(evt, ui) {
        // To attribute the new index number, we need to get the DOM element
        // of the previous and the following card -- if any.
        const prevBoardDom = ui.item.prev('.js-board').get(0);
        const nextBoardBom = ui.item.next('.js-board').get(0);
        const sortIndex = calculateIndex(prevBoardDom, nextBoardBom, 1);

        const boardDomElement = ui.item.get(0);
        const board = Blaze.getData(boardDomElement);
        // Normally the jquery-ui sortable library moves the dragged DOM element
        // to its new position, which disrupts Blaze reactive updates mechanism
        // (especially when we move the last card of a list, or when multiple
        // users move some cards at the same time). To prevent these UX glitches
        // we ask sortable to gracefully cancel the move, and to put back the
        // DOM in its initial state. The card move is then handled reactively by
        // Blaze with the below query.
        $boards.sortable('cancel');

        board.move(sortIndex.base);
      },
    });

    // ugly touch event hotfix
    enableClickOnTouch(itemsSelector);

    const itemsSelectorMindMap = '.js-mindMap:not(.placeholder)';

    const $mindMaps = this.$('.js-mindMaps');
    $mindMaps.sortable({
      connectWith: '.js-mindMaps',
      tolerance: 'pointer',
      appendTo: '.board-list',
      helper: 'original',
      distance: 7,
      items: itemsSelectorMindMap,
      placeholder: 'board-wrapper placeholder',
      start(evt, ui) {
        ui.helper.css('z-index', 1000);
        ui.placeholder.height(ui.helper.height());
        EscapeActions.executeUpTo('popup-close');
      },
      stop(evt, ui) {
        // To attribute the new index number, we need to get the DOM element
        // of the previous and the following card -- if any.
        const prevBoardDom = ui.item.prev('.js-mindMap').get(0);
        const nextBoardBom = ui.item.next('.js-mindMap').get(0);
        const sortIndex = calculateIndex(prevBoardDom, nextBoardBom, 1);

        const boardDomElement = ui.item.get(0);
        const mindMap = Blaze.getData(boardDomElement);
        // Normally the jquery-ui sortable library moves the dragged DOM element
        // to its new position, which disrupts Blaze reactive updates mechanism
        // (especially when we move the last card of a list, or when multiple
        // users move some cards at the same time). To prevent these UX glitches
        // we ask sortable to gracefully cancel the move, and to put back the
        // DOM in its initial state. The card move is then handled reactively by
        // Blaze with the below query.
        $mindMaps.sortable('cancel');

        mindMap.move(sortIndex.base);
      },
    });

    // ugly touch event hotfix
    enableClickOnTouch(itemsSelectorMindMap);

    // Disable drag-dropping if the current user is not a board member or is comment only
    this.autorun(() => {
      if (Utils.isMiniScreen()) {
        $boards.sortable({
          handle: '.board-handle',
        });
        $mindMaps.sortable({
          handle: '.board-handle',
        });
      }
    });
  },
  onCreated() {
    Meteor.subscribe('setting');
  },
  boards() {
    const query = {
      archived: false,
      type: 'board',
    };
    if (FlowRouter.getRouteName() === 'newHome')
      query['members.userId'] = Meteor.userId();
    else query.permission = 'public';

    const Boardsw = Boards.find(query, {
      sort: { sort: 1 /* boards default sorting */ },
    });
    return Boardsw;
  },
  // publicBoards() {
  //   const query = {
  //     archived: false,
  //     type: 'board',
  //   };
  //   query.permission = 'public';

  //   const Boardsw = Boards.find(query, {
  //     sort: { sort: 1 /* boards default sorting */ },
  //   });
  //   return Boardsw;
  // },
  mindMaps() {
    const query = {
      archived: false,
      userId: Meteor.userId(),
    };
    const mindMaps = MindMaps.find(query, {
      sort: { sort: 1 /* boards default sorting */ },
    });
    return mindMaps;
  },
  exportUrl() {
    // const params = {
    //   boardId: Session.get(''),
    //   name: ,
    //   userId: Meteor.userId(),
    // };
    // const queryParams = {
    //   authToken: Accounts._storedLoginToken(),
    // };
    // return FlowRouter.path('/mindMap/dist/index.html', params, queryParams);
    const exportUrl = '/mindMap/dist/index.html';
    return exportUrl;
  },
  // starredBoards() {
  //   const user = Meteor.user();
  //   return user && user.starredBoards();
  // },
  isStarred() {
    const user = Meteor.user();
    return user && user.hasStarred(this.currentData()._id);
  },
  isAdministrable() {
    const user = Meteor.user();
    return user && user.isBoardAdmin(this.currentData()._id);
  },

  hasOvertimeCards() {
    subManager.subscribe('board', this.currentData()._id, false);
    return this.currentData().hasOvertimeCards();
  },

  hasSpentTimeCards() {
    subManager.subscribe('board', this.currentData()._id, false);
    return this.currentData().hasSpentTimeCards();
  },

  isInvited() {
    const user = Meteor.user();
    return user && user.isInvitedTo(this.currentData()._id);
  },

  events() {
    return [
      {
        'click .icon-zhankai'() {
          clearTimeout(timer);
          clearTimeout(timer1);
          if (flag == true) {
            for (
              let i = 0;
              i < document.querySelectorAll('.list2').length;
              i++
            ) {
              document.querySelectorAll('.list2')[i].style.display = 'none';
            }
            for (let i = 0; i < document.querySelectorAll('.nav').length; i++) {
              //document.querySelectorAll('.nav')[i].style.display = 'none';
              document.querySelectorAll('.nav')[i].style.transition = 'all 0s';
              document.querySelectorAll('.nav')[i].style.height = '0px';
            }
            for (
              let i = 0;
              i < document.querySelectorAll('.icon-xiaoyuhao-').length;
              i++
            ) {
              document.querySelectorAll('.icon-xiaoyuhao-')[i].style.display =
                'none';
              // document.querySelectorAll('.icon-xiaoyuhao-')[i].style.transform="rotate(0deg);";
            }
            document.querySelector('.icon-zhankai').style.marginLeft = '0px';
            document.querySelector('.icon-zhankai').style.transition =
              'all 0.3s';
            // document.querySelectorAll('.nav').style.display="none";
            document.querySelector('.aside').classList.remove('fold1');
            document.querySelector('.aside').classList.add('fold');
            //  // document.querySelector('.aside').classList.remove('fold-1');
            //   document.querySelector('.aside').classList.add('fold-1');
            // clearInterval(timer);
            // clearInterval(timer1);
            // document.querySelector('.aside').style.display = 'none';
            // document.querySelector('.aside').style.transition="all 0.5";
            // document.querySelector('.aside1').style.display = 'block';
            // document.querySelector('.aside1').classList.remove("fold1");
            // document.querySelector('.aside1').classList.add("fold");
            // document.querySelector('.aside1').style.width = '70px';

            // document.querySelector(".aside1").style.transition="all 1s"
            flag = false;
            flag1 = false;
            document.getElementsByClassName('icon-zhankai')[0].style.transform =
              'rotate(180deg)';
            //if(flag3==true){
            document.querySelector('.home-content').style.marginLeft = '170px';
            document.querySelector('.home-content').style.transition =
              'all 0.3s';
            //  }else{
            //   console.log("Zep");
            //   document.querySelector('.home-content').style.marginLeft = '70px';
            //   document.querySelector('.home-content').style.transition =
            //     'all 0.3s';
            // }
            // document.getElementsByClassName(
            //   'home-content',
            // )[0].style.marginLeft = '170px';
            // document.getElementsByClassName(
            //   'home-content',
            // )[0].style.transition = 'all 0.3s';
          } else {
            const navlists = document.getElementsByClassName('navlist');
            for (let i = 1; i < navlists.length; i++) {
              navlists[i].querySelector('span').style.transform =
                'rotate(90deg)';
              flag2 = false;
            }
            document.querySelector('.aside').classList.remove('fold');
            document.querySelector('.aside').classList.add('fold1');
            timer = window.setTimeout(function() {
              for (
                let i = 0;
                i < document.querySelectorAll('.list2').length;
                i++
              ) {
                document.querySelectorAll('.list2')[i].style.display =
                  'inline-block';
              }
              for (
                let i = 0;
                i < document.querySelectorAll('.icon-xiaoyuhao-').length;
                i++
              ) {
                document.querySelectorAll('.icon-xiaoyuhao-')[i].style.display =
                  'block';
              }
            }, 300);

            // for(let i= 0;i< document.querySelectorAll('.nav').length;i++){
            //   document.querySelectorAll('.nav')[i].style.display="block";
            // }
            document.querySelector('.icon-zhankai').style.marginLeft = '200px';
            document.querySelector('.icon-zhankai').style.transition =
              'all 0.3s';
            document.getElementsByClassName('icon-zhankai')[0].style.transform =
              'rotate(0deg)';
            document.getElementsByClassName(
              'home-content',
            )[0].style.marginLeft = '270px';
            // document.querySelector(".aside1").style.transition="all 1s"
            // document.querySelector(".aside1").classList.add("aside2");
            // document.querySelector('.aside1').classList.remove("fold");
            // document.querySelector('.aside1').classList.add("fold1");
            // timer = window.setInterval(function(){
            //   //document.querySelector('.aside').style.transition="all 1s";
            //   document.querySelector('.aside').style.display = 'block';
            // },800)
            // timer1 = window.setInterval(function(){
            //   document.querySelector('.aside1').style.display = 'none';
            // },700)
            flag = true;
            flag1 = true;
          }
        },
        'click .js-add-board': Popup.open('createBoard'),
        'click .js-star-board'(evt) {
          const boardId = this.currentData()._id;
          Meteor.user().toggleBoardStar(boardId);
          evt.preventDefault();
        },
        // 'click .js-clone-board'(evt) {
        //   Meteor.call(
        //     'copyBoard',
        //     this.currentData()._id,
        //     {
        //       sort: Boards.find({ archived: false }).count(),
        //       type: 'board',
        //       title: Boards.findOne(this.currentData()._id).title,
        //     },
        //     (err, res) => {
        //       if (err) {
        //         this.setError(err.error);
        //       } else {
        //         Session.set('fromBoard', null);
        //         Utils.goBoardId(res);
        //       }
        //     },
        //   );
        //   evt.preventDefault();
        // },
        'click .js-clone-board': Popup.afterConfirm('boardClone', function(
          evt,
        ) {
          Popup.close();
          Meteor.call(
            'copyBoard',
            this._id,
            {
              sort: Boards.find({ archived: false }).count(),
              type: 'board',
              title: Boards.findOne(this._id).title,
            },
            (err, res) => {
              if (err) {
                this.setError(err.error);
              } else {
                Session.set('fromBoard', null);
                Utils.goBoardId(res);
              }
            },
          );
          evt.preventDefault();
        }),
        // 'click .js-archive-board'(evt) {
        //   const boardId = this.currentData()._id;
        //   Meteor.call('archiveBoard', boardId);
        //   evt.preventDefault();
        // },
        'click .js-archive-board': Popup.afterConfirm(
          'boardArchive',
          function() {
            Popup.close();
            const boardId = this._id;
            Meteor.call('archiveBoard', boardId);
            evt.preventDefault();
          },
        ),
        'click .js-accept-invite'() {
          const boardId = this.currentData()._id;
          Meteor.call('acceptInvite', boardId);
        },
        'click .js-decline-invite'() {
          const boardId = this.currentData()._id;
          Meteor.call('quitBoard', boardId, (err, ret) => {
            if (!err && ret) {
              Meteor.call('acceptInvite', boardId);
              if (Utils.isMiniScreen()) {
                FlowRouter.go('home');
              } else {
                FlowRouter.go('newHome');
              }
            }
          });
        },
        'click .js-add-mindmap': Popup.open('createMindMap'),
        'mouseenter .js-add-mindmap'() {
          document.body.style.backgroundColor = '';
          document.body.style.backgroundImage =
            "url('./public/../main_backgroundColor.jpg')";
          document.body.style.backgroundSize = 'cover';
          document.body.style.backgroundRepeat = 'no-repeat';
        },
        // 'click .js-mindMap'() {
        //   const mindMapId = this.currentData()._id;
        //   const mindMapUrl = `/mindMap/dist/index.html?mindMapId=${mindMapId}`;
        //   window.location.href = mindMapUrl;
        // },
        // 'click .js-archive-mindMap'(evt) {
        //   window.confirm("确认删除该脑图吗？删除脑图的操作不可逆。");
        //   const mindMapId = this.currentData()._id;
        //   Meteor.call('archiveMindMap', mindMapId);
        //   evt.preventDefault();
        //   evt.stopPropagation();
        // },
        // 'click .js-archive-mindMap': Popup.afterConfirm('mindMapDelete', function() {
        //     Popup.close();
        //     const mindMapId = this._id;
        //     Meteor.call('archiveMindMap', mindMapId);
        //     if (Utils.isMiniScreen()) {
        //       FlowRouter.go('home');
        //     } else {
        //       FlowRouter.go('newHome');
        //     }
        //   },
        // ),
        'mousedown .js-mindMap'() {
          const mindMapId = this.currentData()._id;
          const mindMapUrl = `/mindMap/dist/index.html?mindMapId=${mindMapId}`;
          window.location.href = mindMapUrl;
        },
        'mousedown .js-archive-mindMap'(evt) {
          evt.stopPropagation();
        },
        'mouseup .js-archive-mindMap': Popup.afterConfirm(
          'mindMapArchive',
          function() {
            Popup.close();
            const mindMapId = this._id;
            Meteor.call('archiveMindMap', mindMapId);
          },
        ),
        'mousedown .js-clone-mindMap'(evt) {
          evt.stopPropagation();
        },
        'mouseup .js-clone-mindMap': Popup.afterConfirm(
          'mindMapClone',
          function(evt) {
            Popup.close();
            Meteor.call(
              'copyMindMap',
              this._id,
              {
                sort: MindMaps.find({ archived: false }).count(),
                name: MindMaps.findOne(this._id).name,
              },
              (err, res) => {
                if (err) {
                  this.setError(err.error);
                } else {
                  const mindMapId = res;
                  const mindMapUrl = `/mindMap/dist/index.html?mindMapId=${mindMapId}`;
                  window.location.href = mindMapUrl;
                }
              },
            );
            evt.preventDefault();
            evt.stopPropagation();
          },
        ),
      },
    ];
  },
}).register('newBoardList');
